package com.example.activiti.component;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;

@Component
public class MailComponent {

    @Autowired
    JavaMailSender mailSender;

    public void sendMail(String to){
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom("1010569623@qq.com");
        message.setTo(to);
        message.setSubject("主题：简单邮件");
        message.setText("测试邮件内容");

        mailSender.send(message);

    }

    public void sendHtmlMail(){
        //获取MimeMessage对象
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper messageHelper;
        try {
            messageHelper = new MimeMessageHelper(message, true);
            //邮件发送人
            messageHelper.setFrom("1010569623@qq.com");
            //邮件接收人
            String[] tos = new String[]{"fisher.fang@lcfuturecenter.com","fang101056@outlook.com"};
            messageHelper.setTo(tos);
            //邮件主题
            message.setSubject("测试html内容");
            //邮件内容，html格式
            messageHelper.setText("你好：</br>&nbsp;&nbsp;有一条待办需要处理", true);
            //发送
            mailSender.send(message);
            //日志信息
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }

    /**
     * 待附件
     * @param to
     * @param subject
     * @param content
     * @param filePath
     */
    public void sendAttachmentsMail(String to, String subject, String content, String filePath) {
        MimeMessage message = mailSender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom("");
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);

            FileSystemResource file = new FileSystemResource(new File(filePath));
            String fileName = filePath.substring(filePath.lastIndexOf(File.separator));
            helper.addAttachment(fileName, file);
            mailSender.send(message);
            //日志信息
        } catch (MessagingException e) {
        }


    }
}
